package com.java.compare;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorUse {
    private String name;
    private Integer age;
    
    public ComparatorUse(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
    
    @Override
    public String toString() {
        return this.age + this.name;
    }
    
    public static void main(String[] args) {
        List<ComparatorUse> list = new ArrayList();
        list.add(new ComparatorUse("MJQ", 21));
        list.add(new ComparatorUse("DCX", 22));
        list.add(new ComparatorUse("SYX", 19));
        list.add(new ComparatorUse("LYW", 18));
        list.add(new ComparatorUse("ZZY", 20));
        list.add(new ComparatorUse("YHX", 19));
        list.add(new ComparatorUse("HJL", 19));
        
        System.out.println(list); // [21MJQ, 22DCX, 19SYX, 18LYW, 20ZZY, 19YHX, 19HJL]
        Collections.sort(list, new Comparator<ComparatorUse>() {
            @Override
            public int compare(ComparatorUse o1, ComparatorUse o2) {
                if (o1.age == o2.age) {
                    // 参数1表示被添加的元素，返回负数时被添加元素放左侧，但返回负数也意味着被添加元素更小，所以是升序排序
                    return o1.name.compareTo(o2.name); // 升序
                }
                
                // 参数1表示被添加的元素，返回负数时被添加元素放左侧，但返回负数也意味着被添加元素更大，所以是降序排序
                return o2.age - o1.age; // 降序
                
                // 升序：参数1 - 参数2
                // 降序：参数2 - 参数1
            }
        });
        System.out.println(list); // [22DCX, 21MJQ, 20ZZY, 19HJL, 19SYX, 19YHX, 18LYW]
    }
}
